package com.etop.weiway.wxmanage.service;

import com.alibaba.fastjson.JSON;
import com.etop.weiway.basic.service.BaseService;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.dao.*;
import com.etop.weiway.wxmanage.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jessy
 */
@Service("MaterialService")
public class MaterialService extends BaseService {

    @Autowired
    private MaterialTextDAO materialTextDAO;
    @Autowired
    private MaterialImageDAO materialImageDao;
    @Autowired
    private MaterialVideoDAO materialVideoDAO;
    @Autowired
    private MaterialVoiceDAO materialVoiceDAO;
    @Autowired
    private MaterialNewsDAO materialNewsDAO;
    @Autowired
    private MaterialMutinewsDAO materialMutinewsDAO;
    @Autowired
    private MaterialImageDAO materialImageDAO;

    public final static int limitedSize_Image = 1024 * 1024;

    /**
     * 使用id获得图片素材
     *
     * @param id
     * @return
     */
    public MaterialImage loadMaterialImage(int id) {
        log.debug("******根据id查询图片素材******");
        return materialImageDAO.get(id);
    }

    public MaterialImage loadMaterialImageByName(String name, int accountId) {
        log.debug("******根据名称查询图片素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialImage t where t.name = :name and t.account.id = " + accountId;
        params.put("name", name);
        return materialImageDAO.findUniqueResult(queryString, params);
    }

    /**
     * 保存或更新图片素材
     *
     * @param materialImage
     */
    public void saveMaterialImage(MaterialImage materialImage, Account account) {
        log.debug("******保存或更新图片素材******");
        materialImage.setAccount(account);
        materialImage.setCreatedTime((long) 0);
        materialImageDAO.saveOrUpdate(materialImage);
    }

    /**
     * 根据id删除图片素材(假删除)
     *
     * @param id
     */
    public void deleteMaterialImageById(int id) {
        log.debug("******根据id删除图片素材******");
        MaterialImage materialImage = materialImageDAO.get(id);
        materialImageDAO.invalid(materialImage);
    }

    /**
     * 分页查询图片素材
     *
     * @param pager
     * @param keyword
     * @return pager<MaterialImage>
     * @throws Exception
     */
    public Pager<MaterialImage> getMaterialImageByPage(Pager<MaterialImage> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询图片素材******");
        Map<String, Object> params = createParamMap();
        String queryString = "from MaterialImage t where t.valid = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.name like :keyword)";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by id desc";
        List<MaterialImage> materialImages = materialImageDAO.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialImageDAO.getTotalCount(queryString, params));
        pager.setList(materialImages);
        return pager;
    }

    /**
     * 分页查询图片素材
     *
     * @param pager
     * @param keyword
     * @return pager<MaterialImage>
     * @throws Exception
     */
    public Pager<MaterialImage> getMaterialThumbByPage(Pager<MaterialImage> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询缩略图素材******");
        Map<String, Object> params = createParamMap();
        String queryString = "from MaterialImage t where t.valid = 1 and t.thumbnail = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.name like :keyword)";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.id desc";
        List<MaterialImage> materialImages = materialImageDAO.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialImageDAO.getTotalCount(queryString, params));
        pager.setList(materialImages);
        return pager;
    }

    public List<MaterialImage> listMaterialThumb(int accountId) {
        String queryString = "from MaterialImage t where t.valid=1 and t.thumbnail = 1 and t.account.id = " + accountId;
        List<MaterialImage> list = materialImageDAO.find(queryString);
        return list;
    }

    /**
     * 使用id获得视频素材
     *
     * @param id
     * @return
     */
    public MaterialVideo loadMaterialVideo(int id) {
        log.debug("******根据id查询视频素材******");
        return materialVideoDAO.get(id);
    }

    public MaterialVideo loadMaterialVideoByName(String name, int accountId) {
        log.debug("******根据名称查询视频素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialVideo t where t.name = :name and t.account.id = " + accountId;
        params.put("name", name);
        return materialVideoDAO.findUniqueResult(queryString, params);
    }

    /**
     * 保存或更新视频素材
     *
     * @param materialVideo
     * @param account
     * @param thumbMediaId
     */
    public void saveMaterialVideo(MaterialVideo materialVideo, Account account, int thumbMediaId) {
        log.debug("******保存或更新视频素材******");
        materialVideo.setAccount(account);
        materialVideo.setThumbMedia(loadMaterialImage(thumbMediaId));
        materialVideo.setCreatedTime((long) 0);
        materialVideoDAO.saveOrUpdate(materialVideo);
    }

    /**
     * 根据id删除视频素材(假删除)
     *
     * @param id
     */
    public void deleteMaterialVideoById(int id) {
        log.debug("******根据id删除视频素材******");
        MaterialVideo materialVideo = materialVideoDAO.get(id);
        materialVideoDAO.invalid(materialVideo);
    }

    /**
     * 分页查询视频素材
     *
     * @param pager
     * @param keyword
     * @return pager<MaterialVideo>
     * @throws Exception
     */
    public Pager<MaterialVideo> getMaterialVideoByPage(Pager<MaterialVideo> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询视频素材******");
        Map<String, Object> params = createParamMap();
        String queryString = "from MaterialVideo t where t.valid = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and t.name like :keyword";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.id desc";
        List<MaterialVideo> materialVideos = materialVideoDAO.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialVideoDAO.getTotalCount(queryString, params));
        pager.setList(materialVideos);
        return pager;
    }

    /**
     * 使用id获得音频素材
     *
     * @param id
     * @return
     */
    public MaterialVoice loadMaterialVoice(int id) {
        log.debug("******根据id查询音频素材******");
        return materialVoiceDAO.get(id);
    }

    public MaterialVoice loadMaterialVoiceByName(String name, int accountId) {
        log.debug("******根据名称查询音频素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialVoice t where t.name = :name and t.account.id = " + accountId;
        params.put("name", name);
        return materialVoiceDAO.findUniqueResult(queryString, params);
    }

    /**
     * 保存或更新音频素材
     *
     * @param materialVoice
     */
    public void saveMaterialVoice(MaterialVoice materialVoice, Account account, int thumbMediaId) {
        log.debug("******保存或更新音频素材******");
        materialVoice.setAccount(account);
        materialVoice.setCreatedTime((long) 0);
        MaterialImage thumbImage = loadMaterialImage(thumbMediaId);
        materialVoice.setThumbMedia(thumbImage);
        materialVoiceDAO.saveOrUpdate(materialVoice);
    }

    /**
     * 根据id删除音频素材(假删除)
     *
     * @param id
     */
    public void deleteMaterialVoiceById(int id) {
        log.debug("******根据id删除音频素材******");
        MaterialVoice materialVoice = materialVoiceDAO.get(id);
        materialVoiceDAO.invalid(materialVoice);
    }

    /**
     * 分页查询音频素材
     *
     * @param pager
     * @param keyword
     * @return pager<MaterialVoice>
     * @throws Exception
     */
    public Pager<MaterialVoice> getMaterialVoiceByPage(Pager<MaterialVoice> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询音频素材******");
        Map<String, Object> params = createParamMap();
        String queryString = "from MaterialVoice t where t.valid = 1 and t.account.id =" + accountId;
//        if(requireVoice){
//             queryString += " and t.isVoice =1"; 
//        }
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and t.name like :keyword ";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.id desc";
        List<MaterialVoice> materialVoices = materialVoiceDAO.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialVoiceDAO.getTotalCount(queryString, params));
        pager.setList(materialVoices);
        return pager;
    }

    /**
     * 处理媒体
     *
     * @param path
     * @param isForNews
     * @param userId
     * @param accountId
     * @param multipartFile
     * @param type
     * @param saveMaterial
     * @return
     */
    public String handleUploadMedia(String path, String isForNews, Integer userId, Integer accountId, MultipartFile multipartFile, String type, String saveMaterial) {
        log.debug("******处理媒体******");
        if (!path.endsWith("/")) {
            path += "/";
        }
        String uuid = null;
        if ("true".equals(isForNews.trim())) {
            path += "home/wxmanage/upload/" + userId + "/image";
            uuid = uploadMedia(multipartFile, path, type);

        } else {
            path += "home/wxmanage/upload/" + userId + "/" + type;
            uuid = uploadMedia(multipartFile, path, type);
            if (saveMaterial.trim().equals("true")) {
                saveTempMaterial(type, uuid, accountId);
            }
        }
        return uuid;
    }

    /**
     * 保存临时素材
     *
     * @param type
     * @param uuid      文件名
     * @param accountId
     */
    public void saveTempMaterial(String type, String uuid, int accountId) {
        Account account = new Account();
        account.setId(accountId);
        switch (type) {
            case "image":
                log.debug("******保存临时图片素材******");
                MaterialImage materialImage = new MaterialImage();
                materialImage.setName(uuid);
                materialImage.setCreatedTime((long) 0);
                materialImage.setThumbnail((short) 0);
                materialImage.setUrl(uuid);
                saveMaterialImage(materialImage, account);
                break;
            case "voice":
                log.debug("******保存临时语音素材******");
                MaterialVoice materialVoice = new MaterialVoice();
                materialVoice.setName(uuid);
                materialVoice.setCreatedTime((long) 0);
                materialVoice.setIsVoice(1);
                materialVoice.setAccount(account);
                materialVoice.setUrl(uuid);
                materialVoiceDAO.saveOrUpdate(materialVoice);
                break;
        }
    }

    public String handleDelMedia(String path, Integer userId, String fileName, String type) {
        if (!path.endsWith("/")) {
            path += "/";
        }
        path += "home/wxmanage/upload/" + userId + "/" + type;
        if (fileName == null || deleteImg(path, fileName)) {
            return "true";
        } else {
            return "error:删除失败！";
        }
    }

    /**
     * 保存文本素材
     *
     * @param materialText
     */
    public void saveMaterialText(MaterialText materialText, Account account) {
        log.debug("******保存或更新文本素材******");
        materialText.setAccount(account);
        materialTextDAO.save(materialText);
    }

    /**
     * 获取所有文本素材（valid为 1）
     *
     * @return
     */
    public List<MaterialText> getMaterialText() {
        List<MaterialText> textList = materialTextDAO.find("from MaterialText mt");
        //显示内容有效的文本
        for (int i = textList.size() - 1; i >= 0; i--) {
            if (textList.get(i).getValid() == 0) {
                MaterialText b = textList.remove(i);
            }
        }
        return textList;
    }

    /**
     * 分页查询文本素材
     *
     * @param pager
     * @return pager<MaterialText>
     * @throws Exception
     * @Pager keyword
     */
    public Pager<MaterialText> getMaterialTextByPager(Pager<MaterialText> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询文本素材******");
        Map<String, Object> params = createParamMap();
        String queryString = "from MaterialText t where t.valid = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and (t.name like :keyword or t.content like :keyword )";
            params.put("keyword", getKeyWords(keyword));
        }
        queryString += " order by t.id desc";
        List<MaterialText> materialTexts = materialTextDAO.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialTextDAO.getTotalCount(queryString, params));
        pager.setList(materialTexts);
        return pager;
    }

    /**
     * 根据id获取文本素材对象
     *
     * @param id
     * @return
     */
    public MaterialText loadMaterialText(int id) {
        log.debug("******根据id查询文本素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialText t where t.valid = 1 and t.id = :id";
        params.put("id", id);
        return materialTextDAO.findUniqueResult(queryString, params);
    }

    public MaterialText loadMaterialTextByName(String name, int accountId) {
        log.debug("******根据名称查询文本素材******");
        Map<String, Object> params = new HashMap<>();
//        String queryString = "from MaterialText t where t.valid = 1 and t.name = :name and t.account.id ="+accountId;
        String queryString = "from MaterialText t where t.valid = 1 and t.name = :name and t.account.id = " + accountId;
        params.put("name", name);
        return materialTextDAO.findUniqueResult(queryString, params);
    }

    /**
     * 根据id删除文本素材
     *
     * @param id
     */
    public void deleteMaterialText(int id) {
        log.debug("******根据id删除文本素材******");
        MaterialText materialText = materialTextDAO.get(id);
        materialTextDAO.invalid(materialText);
    }

    /**
     * 保存图文素材
     *
     * @param materialNews
     */
    public void saveMaterialNews(MaterialNews materialNews, String portrait, String thumbMediaId, Account account) throws Exception {
        log.debug("******保存图文素材******");
        //上传的图文参数传递通过页面传过来
        MaterialImage materialThumb = new MaterialImage();
        if (portrait != null && !portrait.equals("")) {
            materialThumb.setThumbnail((short) 1);
            materialThumb.setUrl(portrait);
            saveMaterialImage(materialThumb, account);
            materialNews.setThumbMedia(materialThumb);
        } else if (thumbMediaId != null && !thumbMediaId.equals("")) {
            materialThumb = loadMaterialImage(Integer.parseInt(thumbMediaId));
            materialNews.setThumbMedia(materialThumb);
        }
        materialNews.setAccount(account);
        materialNews.setCreatedTime((long) 0);
        materialNewsDAO.save(materialNews);
    }

    /**
     * 分页获取单图文素材
     *
     * @param pager
     * @param keyword
     * @param accountId
     * @return
     * @throws Exception
     */
    public Pager<MaterialNews> getMaterialNewsByPager(Pager<MaterialNews> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询单图文素材******");
        String queryString = "from MaterialNews t where t.valid = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and t.name like '%" + keyword + "%'";
        }
        queryString += " order by t.id desc";
        List<MaterialNews> materialNewses = materialNewsDAO.find(queryString, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(materialNewsDAO.getTotalCount(queryString));
        pager.setList(materialNewses);
        return pager;
    }

    /**
     * 获取所有图文素材
     *
     * @return
     */
    public String getMaterialNews(int accountId) {
        log.debug("******普通获取所有图文素材json数据******");
        String queryString = "from MaterialNews t where valid=1 and t.account.id = :id";
        Map<String, Object> map = this.createParamMap();
        map.put("id", accountId);
        List<MaterialNews> list = materialNewsDAO.find(queryString, map);
        String jsonNews = JSON.toJSONString(list, true);
        return jsonNews;
    }

    /**
     * 根据id获取单图文消息
     *
     * @param id
     * @return
     */
    public MaterialNews loadMaterialNews(Integer id) {
        log.debug("******根据id获取图文素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialNews t where t.valid = 1 and t.id = :id";
        params.put("id", id);
        return materialNewsDAO.findUniqueResult(queryString, params);
    }

    /**
     * 根据标题获取单图文
     *
     * @param title
     * @return
     */
    public MaterialNews loadMaterialNewsByTitle(String title) {
        log.debug("******根据标题获得图文素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialNews t where t.valid = 1 and t.title = :title";
        params.put("title", title);
        return materialNewsDAO.findUniqueResult(queryString, params);

    }

    /**
     * 根据素材名称获取单图文
     *
     * @param name
     * @return
     */
    public MaterialNews loadMaterialNewsByName(String name) {
        log.debug("******根据素材名称获得图文素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialNews t where t.valid = 1 and t.name = :name";
        params.put("name", name);
        return materialNewsDAO.findUniqueResult(queryString, params);
    }

    /**
     * 根据素材名称获取多图文
     *
     * @param name
     * @param accountId
     * @return
     */
    public MaterialMutinews loadMaterialMutinewsByName(String name, int accountId) {
        log.debug("******根据素材名称获得多图文素材******");
        Map<String, Object> params = new HashMap<>();
        String queryString = "from MaterialMutinews t where t.valid = 1 and t.name = :name and t.account.id = " + accountId;
        params.put("name", name);
        return materialMutinewsDAO.findUniqueResult(queryString, params);
    }

    /**
     * 删除单图文消息
     *
     * @param id
     */
    public void deleteMaterialNews(Integer id) {
        log.debug("******删除单图文素材******");
        MaterialNews materialNews = materialNewsDAO.get(id);
        //删除对应多图文 edit by jeremie 2015/2/1
        List<MaterialMutinews> materialMutinewses = materialMutinewsDAO.find("from MaterialMutinews t where t.valid = 1 and t.multIds like '%" + materialNews.getId() + "%'");
        for (MaterialMutinews materialMutinews : materialMutinewses) {
            String ids = materialMutinews.getMultIds();
            if (ids.contains("," + id.toString()) || ids.contains(id.toString() + ",")) {
                materialMutinewsDAO.invalid(materialMutinews);
            }
        }
        materialNewsDAO.invalid(materialNews);


    }

    /**
     * 根据id获取多图文消息
     *
     * @param id
     * @return
     */
    public MaterialMutinews loadMaterialMutinews(Integer id) throws CloneNotSupportedException {
        log.debug("******根据id删除多图文素材******");
        MaterialMutinews materialMutinews = materialMutinewsDAO.get(id);
        materialMutinews.setMaterialNewses(getMaterialNewsByMultIds(materialMutinews.getMultIds()));
        return materialMutinews;
    }

    /**
     * 保存多图文消息
     *
     * @param materialMutinews
     * @param account
     * @param newsID
     * @throws java.lang.CloneNotSupportedException
     */
    public void saveMaterialMutinews(MaterialMutinews materialMutinews, Account account, String newsID) throws CloneNotSupportedException {
        log.debug("******保存多图文素材******");
        materialMutinews.setAccount(account);
        materialMutinews.setCreatedTime((long) 0);
        materialMutinews.setMultIds(newsID.substring(0, newsID.length() - 1));
        materialMutinews.setMaterialNewses(getMaterialNewsByMultIds(newsID.substring(0, newsID.length() - 1)));
        materialMutinewsDAO.saveOrUpdate(materialMutinews);
    }

    /**
     * 删除多图文消息
     *
     * @param id
     */
    public void deleteMaterialMutinews(Integer id) {
        log.debug("******根据id删除文本素材******");
        MaterialMutinews materialMutinews = materialMutinewsDAO.get(id);
        materialMutinewsDAO.invalid(materialMutinews);
    }

    /**
     * 分页获取多图文素材
     *
     * @param accessToken
     * @param pager
     * @param keyword
     * @param accountId
     * @return
     * @throws Exception
     */
    public Pager<MaterialMutinews> getMaterialMutinewsByPager(String accessToken, Pager<MaterialMutinews> pager, String keyword, int accountId) throws Exception {
        log.debug("******根据条件查询图文素材******");
        String queryString = "from MaterialMutinews t where t.valid = 1 and t.account.id = " + accountId;
        if (!StringUtils.isEmpty(keyword)) {
            queryString += " and t.name like '%" + keyword + "%'";
        }
        queryString += " order by t.id desc";
        List<MaterialMutinews> materialMutinewsList = materialMutinewsDAO.find(queryString, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        for (MaterialMutinews materialMutinews : materialMutinewsList) {
            materialMutinews.setMaterialNewses(getMaterialNewsByMultIds(materialMutinews.getMultIds()));
        }
        pager.setList(materialMutinewsList);
        pager.setCount(materialMutinewsDAO.getTotalCount(queryString));

        return pager;
    }

    /**
     * 根据multIds获取多图文素材中的单图文列表
     *
     * @param multIds
     * @return
     * @throws CloneNotSupportedException
     */
    public List<MaterialNews> getMaterialNewsByMultIds(String multIds) throws CloneNotSupportedException {
        log.debug("******根据multids获取getMaterialNewsByMultIds多图文素材中单图文集合******");
        List<MaterialNews> materialNewses = new ArrayList();
        if (!StringUtils.isEmpty(multIds)) {
            for (String id : multIds.split(",")) {
                if (!StringUtils.isEmpty(id)) {
                    materialNewses.add((MaterialNews) loadMaterialNews(Integer.parseInt(id)).clone());
                }
            }
        }
        return materialNewses;
    }

    /**
     * 包装回显多图文的大标题图文
     *
     * @param materialMutinews
     * @return
     */
    public MaterialNews getMutinews_firstNews(MaterialMutinews materialMutinews) {
        //总是保存第一个id的图文 前台作为大标题图文
        String firstId = "";
        if (materialMutinews.getMultIds().contains(",")) {
            firstId = materialMutinews.getMultIds().split(",")[0];
        } else {
            firstId = materialMutinews.getMultIds();
        }
        MaterialNews firstNews = null;
        if (!firstId.equals("")) {
            firstNews = loadMaterialNews(Integer.parseInt(firstId));
        }
        return firstNews;
    }

    /**
     * 包装回显多图文的小标题图文的信息
     *
     * @param materialMutinews
     * @return
     */
    public List<MaterialNews> getMutinews_remainNewses(MaterialMutinews materialMutinews) throws CloneNotSupportedException {
        //除了大标题后的剩下作为小标题的图文
        List<MaterialNews> remainNewses = this.getMaterialNewsByMultIds(materialMutinews.getMultIds());
        remainNewses.remove(0);
        return remainNewses;
    }

    /**
     * 以下都是用于异步请求json数据
     */
    /**
     * 获取所有图文素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialNews(int accountId, int startIndex, int pageSize) {
        log.debug("******获取图文素材json数据******");
        String queryString = "from MaterialNews t where valid=1 and t.account.id = :id order by t.id desc";
        Map<String, Object> map = this.createParamMap();
        map.put("id", accountId);
        List<MaterialNews> list = materialNewsDAO.find(queryString, map);
        int totalCount = list.size();
        List<MaterialNews> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialNews emptyMaterialNews = new MaterialNews();
        emptyMaterialNews.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialNews);
        String jsonNews = JSON.toJSONString(jsonList, true);
        return jsonNews;
    }

    /**
     * 获取当前公众号的多图文json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     * @throws CloneNotSupportedException
     */
    public String getMaterialMutinews(int accountId, int startIndex, int pageSize) throws CloneNotSupportedException {
        log.debug("*************获取当前公众号的多图文***********");
        String queryString = "from MaterialMutinews t where t.valid=1 and t.account.id = " + accountId + " order by t.id desc";
        List<MaterialMutinews> list = materialMutinewsDAO.find(queryString);
        for (MaterialMutinews materialMutinews : list) {
            List<MaterialNews> newsList = getMaterialNewsByMultIds(materialMutinews.getMultIds());
            materialMutinews.setMaterialNewses(newsList);
        }
        int totalCount = list.size();
        List<MaterialMutinews> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialMutinews emptyMaterialMutinews = new MaterialMutinews();
        emptyMaterialMutinews.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialMutinews);
        String jsonMutinews = JSON.toJSONString(jsonList, true);
        return jsonMutinews;
    }

    /**
     * 获取文本素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialText(int accountId, int startIndex, int pageSize) {
        log.debug("*************获取当前公众号所有的text***********");
        String queryString = "from MaterialText t where t.valid=1 and t.account.id = " + accountId + " order by t.id desc";
        List<MaterialText> list = materialTextDAO.find(queryString);
        int totalCount = list.size();
        List<MaterialText> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialText emptyMaterialText = new MaterialText();
        emptyMaterialText.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialText);
        String jsonText = JSON.toJSONString(jsonList, true);
        return jsonText;
    }

    /**
     * 获取图片（仅包括缩略图）素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialThumb(int accountId, int startIndex, int pageSize) {
        log.debug("*************获取当前公众号的缩略图***********");
        String queryString = "from MaterialImage t where t.valid=1 and t.thumbnail = 1 and t.account.id = " + accountId + " order by t.id desc";
        List<MaterialImage> list = materialImageDAO.find(queryString);
        int totalCount = list.size();
        List<MaterialImage> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialImage emptyMaterialImage = new MaterialImage();
        emptyMaterialImage.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialImage);
        String jsonImage = JSON.toJSONString(jsonList, true);
        return jsonImage;
    }

    /**
     * 获取图片（不包括缩略图）素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialImage(int accountId, int startIndex, int pageSize) {
        log.debug("*************获取当前公众号的图片***********");
        String queryString = "from MaterialImage t where t.valid=1 and t.thumbnail = 0 and t.account.id = " + accountId + " order by t.id desc";
        List<MaterialImage> list = materialImageDAO.find(queryString);
        int totalCount = list.size();
        List<MaterialImage> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialImage emptyMaterialImage = new MaterialImage();
        emptyMaterialImage.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialImage);
        String jsonImage = JSON.toJSONString(jsonList, true);
        return jsonImage;
    }

    /**
     * 获取视频素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialVideo(int accountId, int startIndex, int pageSize) {
        log.debug("*************获取当前公众号的视频***********");
        String queryString = "from MaterialVideo t where t.valid=1 and t.account.id = " + accountId + " order by t.id desc";
        List<MaterialVideo> list = materialVideoDAO.find(queryString);
        int totalCount = list.size();
        List<MaterialVideo> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialVideo emptyMaterialVideo = new MaterialVideo();
        emptyMaterialVideo.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialVideo);
        String jsonVideo = JSON.toJSONString(jsonList, true);
        return jsonVideo;
    }

    /**
     * 获取音频（仅语音）素材的json数据
     *
     * @param accountId
     * @param startIndex
     * @param pageSize
     * @return
     */
    public String getMaterialVoice(int accountId, int startIndex, int pageSize) {
        log.debug("*************获取当前公众号的voice素材(仅限语音)***********");
        String queryString = "from MaterialVoice t where t.valid=1 and t.isVoice =1 and t.account.id =" + accountId + " order by t.id desc ";
        List<MaterialVoice> list = materialVoiceDAO.find(queryString);
        int totalCount = list.size();
        List<MaterialVoice> jsonList = new ArrayList<>();
        for (int i = startIndex; i < startIndex + pageSize && i < totalCount; i++) {
            jsonList.add(list.get(i));
        }
        MaterialVoice emptyMaterialVoice = new MaterialVoice();
        emptyMaterialVoice.setName(String.valueOf(totalCount));
        jsonList.add(emptyMaterialVoice);
        String jsonVoice = JSON.toJSONString(jsonList, true);
        return jsonVoice;
    }

}
